# 数据库工具类
from contextlib import nullcontext
from platform import python_branch
import peewee
# 异步
import peewee_async
# 时间类型
import datetime

# 导入序列化工具
from playhouse.shortcuts import model_to_dict

# 连接mongo数据库
import pymongo

# python的时区库
import pytz

# 设置时区
tzinfo = pytz.timezone('Asia/Shanghai')


# 连接mongo的数据库 类

class MyMongo:

    def __init__(self, tablename='code'):
        # 数据库连接
        self.client = pymongo.MongoClient(host='localhost', port=27017, tz_aware=True, tzinfo=tzinfo)

        # 声明数据库
        self.db = self.client.mytornado
        if tablename == 'code':
            self.table = self.db.code

        if tablename == 'user':
            self.table = self.db.user

        if tablename == 'img':
            self.table = self.db.img

        if tablename == 'channel':
            self.table = self.db.channel

    # 删除数据
    def remove(self, data):
        return self.table.delete_one(data)

    # 插入数据
    def insert(self, data):

        return self.table.insert_one(data)

    # 查询单个数据
    def find_one(self, data):

        res = self.table.find_one(data)

        return res

    # 查询多个数据
    def find(self, data):

        res = self.table.find(data)

        return res

    # 修改数据
    def update(self, find, field, data):
        # 先查询
        mydata = self.table.find_one(find)
        # 指定字段
        mydata[field] = data
        # 修改
        res = self.table.update_one(find, {'$set': mydata})
        return res


# mymongo = MyMongo('code')

# 删除
# mymongo.remove({'name': 1})


# 修改数据
# mymongo.update({'sid':5},'sid',3)

# 查询多个
# res = mymongo.find({})
# for i in res:
#     print(i['sid'])
#     print(i['imglist'])

# 插入数据
# mymongo.insert({'datetime':tzinfo.localize(datetime.datetime.now()),'code':4561,'email':'123456@qq.com'})

# 查询数据
# res = mymongo.find_one({'email':'123456@qq.com'})
# print(res['code'])
# print(type(res))


# 序列器(单个序列化)
def myser(model, many=False):
    # 判断
    if many == False:

        # 第一次转换
        mymodel = model_to_dict(model)

        return mymodel
    # 多个
    else:
        # 多个转换

        return list(model.dicts())


# 创建数据库连接对象
# 数据库连接池
database = peewee_async.PooledMySQLDatabase("mytronadox", host='127.0.0.1', port=3306, user='root', password='.')


# 设置数据库类

class Test_User(peewee.Model):
    username = peewee.CharField(null=False, default=None)
    password = peewee.CharField(null=False, default=None)

    class Meta:
        database = database


class Test_Role(peewee.Model):
    role = peewee.CharField(null=False, default=None)

    class Meta:
        database = database


class Test_role_user(peewee.Model):
    userid = peewee.IntegerField(null=False, default=0)
    roleid = peewee.IntegerField(null=False, default=0)

    class Meta:
        database = database


# Test_User.create_table(True)
# Test_Role.create_table(True)
# Test_role_user.create_table(True)

# 广告发布表单
class Ad_publishing(peewee.Model):
    title = peewee.CharField(null=False, default=None)  # 广告标题

    uid = peewee.IntegerField(null=False, default=0)  # 用户

    description = peewee.TextField()  # 广告描述

    ad_form = peewee.CharField(null=False, default=None)  # 广告形式类型

    ad_filename = peewee.CharField(null=False, default=None)  # 广告文件名称

    ad_filename_type = peewee.CharField(null=False, default=None)  # 广告文件类型

    ad_location = peewee.CharField(null=False, default=None)  # 广告位置

    ad_industry = peewee.CharField(null=False, default=None)  # 广告行业类型

    time = peewee.DateTimeField(default=datetime.datetime.now())  # 到期时间

    state = peewee.IntegerField(null=False, default=0)  # 状态  默认0没到期

    ad_type = peewee.CharField(null=False, default=None)  # 付费类型

    expenses = peewee.FloatField()  # 费用

    address = peewee.CharField(null=False, default=None)  # 落地页

    cost = peewee.FloatField()  # 成本

    bili = peewee.IntegerField(null=False, default=0)   # 权重

    count = peewee.IntegerField(null=False, default=0)   # 访问次数


# 退款记录表
class Refund(peewee.Model):
    orderid = peewee.IntegerField(null=False, default=0)
    date = peewee.DateTimeField(default=datetime.datetime.now())
    price = peewee.IntegerField(null=False, default=0)
    uid = peewee.IntegerField(null=False, default=0)

    class Meta:
        database = database


# 用户_标签表
class User_tag(peewee.Model):
    # 接口说明

    uid = peewee.IntegerField(null=False, default=0)

    tag_id = peewee.IntegerField(null=False, default=0)

    class Meta:
        database = database


# 标签表
class Tag(peewee.Model):
    # 接口说明

    title = peewee.CharField(null=False, default=None)

    class Meta:
        database = database


# 客服言语记录表
class Client_Stiment(peewee.Model):
    # 接口说明

    text = peewee.CharField(null=False, default=None)

    stimen = peewee.IntegerField(null=False, default=0)

    uid = peewee.IntegerField(null=False, default=0)

    class Meta:
        database = database


# Client_Stiment.create_table(True)

# 订单表
class Order_1(peewee.Model):
    # 接口说明
    orderid = peewee.IntegerField(null=False, default=0)

    uid = peewee.IntegerField(null=False, default=0)

    price = peewee.IntegerField(null=False, default=0)

    date = peewee.DateTimeField(default=datetime.datetime.now())
    state = peewee.IntegerField(null=False, default=0)

    class Meta:
        database = database


# 订单表
class Order_2(peewee.Model):
    # 接口说明
    orderid = peewee.IntegerField(null=False, default=0)

    uid = peewee.IntegerField(null=False, default=0)

    price = peewee.IntegerField(null=False, default=0)
    date = peewee.DateTimeField(default=datetime.datetime.now())
    state = peewee.IntegerField(null=False, default=0)

    class Meta:
        database = database


# 订单表
class Order_3(peewee.Model):
    # 接口说明
    orderid = peewee.IntegerField(null=False, default=0)

    uid = peewee.IntegerField(null=False, default=0)

    price = peewee.IntegerField(null=False, default=0)
    date = peewee.DateTimeField(default=datetime.datetime.now())
    state = peewee.IntegerField(null=False, default=0)

    class Meta:
        database = database


# Order_3.create_table(True)
# Order_2.create_table(True)
#
# Order_1.create_table(True)

# 接口资源路径表
class Uri(peewee.Model):
    # 接口说明
    name = peewee.CharField(null=False, default=None)
    url = peewee.CharField(null=False, default=None)

    class Meta:
        database = database


# 多对多第三张表
class Node_Uri(peewee.Model):
    nodeid = peewee.IntegerField(null=False, default=None)
    urlid = peewee.IntegerField(null=False, default=None)

    class Meta:
        database = database


# Uri.create_table(True)
# Node_Uri.create_table(True)


# Node功能节点表
class Node(peewee.Model):
    # 功能名称
    name = peewee.CharField(null=False, default=None)

    # byte二进制代码
    byte = peewee.IntegerField(null=False, default=0)

    class Meta:
        database = database


# 功能节点表  用户表关联
class Node_User(peewee.Model):
    # 用户id
    uid = peewee.CharField(null=False, default=0)

    # 功能节点id
    nodeid = peewee.CharField(null=False, default=0)

    class Meta:
        database = database


# Node.create_table(True)
# Node_User.create_table(True)


# 角色表
class Role(peewee.Model):
    # 字段
    name = peewee.CharField(null=False, default=None)
    # 用户审核字段  商户后台: {'passport':'营业执照副本'}
    #               运营    : {'id':'工作证'}
    #               流量平台: {'os':'平台资质'}
    audit = peewee.CharField(null=False, default=None)
    # 二进制标识码(所代表的权限)
    byte = peewee.IntegerField(null=False, default=0)

    class Meta:
        database = database


# 用户与角色表
class User_Role(peewee.Model):
    # uid字段
    # roleid字段
    uid = peewee.IntegerField(null=False, default=0)
    roleid = peewee.IntegerField(null=False, default=0)

    class Meta:
        database = database


# User_Role.create_table(True)


# 用户表
class User(peewee.Model):
    # 字段
    username = peewee.CharField(null=False, default=None)
    password = peewee.CharField(null=False, default=None)

    # 用户类型      1商户后台      2运营后台      3流量平台
    type = peewee.IntegerField(null=False, default=0)

    # 年龄
    age = peewee.IntegerField(null=False, default=0)

    # 用户审核字段  商户后台: {'passport':'营业执照副本'}
    #               运营    : {'id':'工作证'}
    #               流量平台: {'os':'平台资质'}
    audit = peewee.CharField(null=False, default=None)

    # 注册时间
    reg = peewee.DateTimeField(default=datetime.datetime.now())

    # 状态,默认 0待审核      1审核通过         2审核拒绝       3审核中
    state = peewee.IntegerField(default=0)

    level = peewee.IntegerField(default=0)

    auid = peewee.IntegerField(null=False, default=0)
    # 客服id
    clientid = peewee.IntegerField(null=False, default=0)
    # abac之属性字段
    sex = peewee.IntegerField(null=False, default=0)
    # 钱包
    wallet = peewee.IntegerField(null=False, default=0)

    class Meta:
        database = database

# User.create_table(True)
# Role.create_table(True)

# 登录查询sql查询
# select * from `user` where username = '' and password = ''

# orm查询  get找不到就会报错
# 单对象
# user = User.select().where ((User.username == '9905') & (User.password == '2')).get()
# print(type(user))
# print(user)
# print(myser(user))
# res = myser(user)
# print(res['username'])

# 多对象
# users = User.select()
# print(type(users))
# print(users)

# res = myser(users,many=True)
# print(res)


# for i in users:
# print(i.username)
# print(myser(users))
# res = myser(users)
# print(res['username'])

# 创建表
# Sub_Talk.create_table(True)
# Subject.create_table(True)
# Talk.create_table(True)


# 删除
# User.drop_table(True)
# exit(-1)

# 添加数据
# res = User.create(username='测试账号',age=20,phone='1234567890')
# print(res)

# 查询
# res = User.get(id=1)


# # 修改
# res.username = '修改账号'
# res.save()

# print(res)

# # 删除         双等   类中的信息     执行
# User.delete().where(User.id == 2).execute()
